package com.bwei.topnews.view;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Toast;

import com.bwei.topnews.utils.CommonUtils;

/**
 * Created by qwe on 2016/11/15.
 */
public class letterView extends View {
    String[] b = {"#", "A", "B", "C", "D", "E", "F", "G", "H", "J", "K",
            "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X",
            "Y", "Z"};
    private int singleheight;
    private int height;
    private int width;
    private String LaseC = "";
    private OnLetterChanggeListener onletterchangelistener;

    public letterView(Context context) {
        super(context);
    }

    public letterView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public letterView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);

    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        height = this.getHeight();
        width = this.getWidth();
        // 计算出给个字母所占大小
        singleheight = height / b.length;

    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        Paint paint = new Paint();
        paint.setColor(Color.WHITE);
        paint.setTextSize(CommonUtils.dip2px(15));
        paint.setAntiAlias(true);
        for (int i = 0; i < b.length; i++) {
            int x = (int) (width / 2 - paint.measureText(b[i]) / 2);
            int y = (int) (singleheight * (i + 1.5));
            canvas.drawText(b[i], x, y, paint);
        }
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
            case MotionEvent.ACTION_MOVE:
                float y = event.getY();
                int ceil = (int) Math.round(y / height * b.length);
                String s = b[ceil-1];
                if (!LaseC.equals(s)) {
                    Toast.makeText(getContext(), s, Toast.LENGTH_SHORT).show();
                    onletterchangelistener.setOnLetterChangge(s);
                    LaseC = s;
                }
                break;
            default:
                LaseC = "";
                break;
        }


        return true;
    }

    public void setOnLetterChangeListener(OnLetterChanggeListener onletterchangelistener) {
        this.onletterchangelistener = onletterchangelistener;
    }
    public interface  OnLetterChanggeListener{
        public void setOnLetterChangge(String letter);
    }
}
